{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pull Portfolio Factor Risk Data with GS Quant\n",
    "\n",
    "**First get your portfolio's factor risk and performance reports:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from IPython.display import display\n",
    "from dateutil.relativedelta import relativedelta\n",
    "import warnings\n",
    "\n",
    "from gs_quant.markets.portfolio_manager import PortfolioManager\n",
    "from gs_quant.markets.report import PerformanceReport, FactorRiskViewsMode, FactorRiskTableMode, FactorRiskUnit\n",
    "from gs_quant.session import GsSession, Environment\n",
    "\n",
    "GsSession.use(Environment.PROD)\n",
    "warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n",
    "\n",
    "\n",
    "portfolio_id = 'MPWQQ8B05FKPCCH6'\n",
    "risk_model_id = 'BARRA_USFAST'\n",
    "\n",
    "\n",
    "pm = PortfolioManager(portfolio_id)\n",
    "risk_report = pm.get_factor_risk_report(risk_model_id)\n",
    "performance_report = pm.get_performance_report()\n",
    "\n",
    "# Uncomment this section to get active risk report instead\n",
    "#benchmark = SecurityMaster.get_asset(id_value='SPX', id_type=AssetIdentifier.BLOOMBERG_ID)\n",
    "#risk_report = PortfolioManager('ENTER PORTFOLIO ID').get_factor_risk_report(risk_model_id='AXWW4M', benchmark_id=benchmark.get_marquee_id())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Now let's plot the portfolio's historical annualized risk:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "risk_data = risk_report.get_view(\n",
    "    start_date=risk_report.latest_end_date - relativedelta(years=1),\n",
    "    end_date=risk_report.latest_end_date)\n",
    "\n",
    "historical_risk = pd.DataFrame(risk_data.get('overviewTimeSeries')).filter(items=['date', 'annualizedExAnteRiskPercent']).set_index('date')\n",
    "historical_risk.rename(columns={'annualizedExAnteRiskPercent': 'Total Risk'}, inplace=True)\n",
    "historical_risk.plot(title='Annualized Risk % (ex-ante)')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Similarly, you can also pull historical proportion of risk in terms of factor and idiosyncratic risk:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "historical_risk = pd.DataFrame(risk_data.get('overviewTimeSeries')).filter(items=['date', 'factorProportionOfRisk', 'specificProportionOfRisk']).set_index('date')\n",
    "historical_risk.rename(columns={'factorProportionOfRisk': 'Factor Risk', 'specificProportionOfRisk': 'Specific Risk'}, inplace=True)\n",
    "historical_risk.plot(title='Factor and Specific Risk')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Then pull the portfolio's risk data by factor category:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "category_table = risk_data.get('factorCategoriesTable')\n",
    "display(pd.DataFrame(category_table).filter(items=['name', 'proportionOfRisk', 'marginalContributionToRiskPercent',\n",
    "                                                   'relativeMarginalContributionToRisk', 'exposure', 'avgProportionOfRisk']))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Now generate the factor risk by asset z-score data:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# Get ZScore Factor Risk by Asset Table\n",
    "zscore_table = risk_report.get_table(mode=FactorRiskTableMode.ZScore)\n",
    "display(pd.DataFrame(zscore_table))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Similarly, create the factor exposure by asset table:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# Get Exposure Factor Risk by Asset Table\n",
    "exposure_table = risk_report.get_table(mode=FactorRiskTableMode.Exposure)\n",
    "display(pd.DataFrame(exposure_table))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Just like the previous two steps, generate the factor risk by asset MCTR data. This time, let's query the percentages instead of the notional values by utilizing the unit parameter:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# Get MCTR Factor Risk by Asset Table\n",
    "mctr_table = risk_report.get_table(mode=FactorRiskTableMode.Mctr, unit=FactorRiskUnit.Percent)\n",
    "display(pd.DataFrame(mctr_table))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Then plot historical proportion of risk across all factor categories:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# Parse Proportion of Risk Timeseries\n",
    "prop_of_risk = risk_report.get_factor_proportion_of_risk(\n",
    "    factor_names=['Market', 'Industry', 'Style'],\n",
    "    start_date=risk_report.latest_end_date - relativedelta(years=1),\n",
    "    end_date=risk_report.latest_end_date).set_index('date')\n",
    "\n",
    "prop_of_risk.plot(title='Proportion of Risk By Factor Category')\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}